﻿#include "CSVFileReadThread.h"
#include "GlobalHeader.h"

CSVFileReadThread::CSVFileReadThread(QObject *parent)
	: QThread(parent)
{
}

CSVFileReadThread::~CSVFileReadThread()
{
}

bool CSVFileReadThread::PutCSVFile(const QString strFilePath)
{
	if (!QFile::exists(strFilePath))
		return false;
	m_FileReadWriteLock.lockForWrite();
	m_QueueFileData.enqueue(strFilePath);
	m_FileReadWriteLock.unlock();
	return true;
}

void CSVFileReadThread::run()
{
// 	if (QFile::exists(m_strCurDealFile))
// 		break;
	gAddLog(LOGTYPE_MESSAGE, u8"开始文件读取线程");
	if (!g_pLineDataDealThread)
		g_pLineDataDealThread = new LineDataDealThread(nullptr);
	if (g_pLineDataDealThread->isFinished() || !g_pLineDataDealThread->isRunning())
		g_pLineDataDealThread->start();
	QString strPath;
	while (!g_bExit && !isInterruptionRequested())
	{
		if (GetCSVFile(strPath))
		{
			QFile CurFile(strPath);
			if (!CurFile.open(QFile::ReadOnly))
			{
				gAddLog(LOGTYPE_ERROR, CurFile.errorString());
				continue;
			}
			qint64 PerDt = QDateTime::currentMSecsSinceEpoch();
			gAddLog(LOGTYPE_MESSAGE, u8"系统正在处理:" + strPath);
			//	QByteArray ByteArrayLineData;
			//第一行表头扔掉
			QTextStream CurTextStream(&CurFile);
			CurTextStream.readLine();
			//while测试
			/*while (!g_bExit && !isInterruptionRequested() && !CurTextStream.atEnd())
			{
				g_pLineDataDealThread->PutLineData(CurTextStream.readLine());
			}*/
			//do while测试
			do 
			{
				g_pLineDataDealThread->PutLineData(CurTextStream.readLine());
			}	 
			while (!g_bExit && !isInterruptionRequested() && !CurTextStream.atEnd());
			CurFile.close();
			QString strLog = u8"文件处理完成:" + strPath;
			strLog += "  用时:" + QString::number(QDateTime::currentMSecsSinceEpoch() - PerDt);
			strLog += "ms";
			gAddLog(LOGTYPE_MESSAGE, strLog);
		}
		else
		{
			QThread::msleep(50);
			if (!g_pDirReadThread || g_pDirReadThread->isFinished())
				break;
		}
	}
	gAddLog(LOGTYPE_MESSAGE, u8"退出文件读取线程");
}

bool CSVFileReadThread::GetCSVFile(QString &strFileData)
{
	m_FileReadWriteLock.lockForRead();
	bool bReturn = false;
	if (m_QueueFileData.isEmpty())
		bReturn = false;
	else
	{
		strFileData = m_QueueFileData.dequeue();
		bReturn = true;
	}
	m_FileReadWriteLock.unlock();
	return bReturn;
}
